import {
  Inject,
  Injectable,
  OnApplicationBootstrap,
  OnModuleInit,
} from "@nestjs/common";
import { createProxyMiddleware, Options } from "http-proxy-middleware";
import { configuration, ProxyServers } from "../../../../config/config";

@Injectable()
export class ProxyService {
  constructor() {}

  setupProxy(app) {
    // let logTable = [];
    // let proxyMap = new Map();
    // ProxyServers.map((eachProxy) => {
    //   const rewritePath = "^" + eachProxy.proxy_path;
    //   logTable.push({
    //     name: eachProxy.system_name,
    //     rewritePath: rewritePath,
    //     targetPort: eachProxy.http_port,
    //   });
    //   const middleware = createProxyMiddleware({
    //     target: `http://localhost:${eachProxy.http_port}`,
    //     pathRewrite: { [rewritePath]: "" },
    //     changeOrigin: true,
    //     on: {
    //       proxyReq: (proxyReq, req, res) => {
    //         /* handle proxyReq */
    //         console.log(new Date().toISOString(), req.url);
    //       },
    //     },
    //   });
    //
    //   proxyMap.set(eachProxy.proxy_path, middleware);
    // });
    // // todo 如果需要在网关中鉴权，那么需要在此处。
    // const server = app.getHttpAdapter().getInstance();
    // for (const [path, middleware] of proxyMap.entries()) {
    //   server.use(path, (req, res, next) => {
    //     middleware(req, res, next);
    //   });
    // }
    // logTable.push({
    //   name: "pacs orthanc",
    //   rewritePath: `^${configuration.gateway.pacs_proxy_path}`,
    //   targetPort: 8042,
    // });
    // server.use(
    //   "/orthanc",
    //   createProxyMiddleware({
    //     target: configuration.pacsServer.url,
    //     changeOrigin: true,
    //     pathRewrite: {
    //       "^/orthanc": "/",
    //     },
    //     on: {
    //       proxyReq: (proxyReq, req, res) => {
    //         /* handle proxyReq */
    //         console.log("proxy req", new Date().toISOString(), req.url);
    //       },
    //       proxyRes: (proxyRes, req, res) => {
    //         console.log("proxy res", new Date().toISOString(), req.url);
    //         proxyRes.headers["Access-Control-Allow-Credentials"] = "true";
    //         proxyRes.headers["Access-Control-Allow-Headers"] =
    //           "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type";
    //         proxyRes.headers["Access-Control-Allow-Methods"] =
    //           "GET, POST, OPTIONS";
    //         proxyRes.headers["Access-Control-Allow-Origin"] = "*";
    //       },
    //     },
    //   } as Options),
    // );
    //
    // console.log("gateway proxy table:");
    // console.table(logTable);
  }
}
